/*
 * 太原学院计算机科学与技术系（C） 版权所有。
 */
package cn.edu.tyu.finance.thingstype.servlet;

import java.io.IOException;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.edu.tyu.util.StringUtil;
import cn.edu.tyu.util.DBUtil;

/**
 * Servlet implementation class AddUserServlet
 */
/**
 * 添加用户
 * @author hujinyu
 *
 */
@WebServlet("/AddUserServlet")
public class AddUserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
    public AddUserServlet() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
    /**
     * 处理网页发来的Get请求
     * @param request 请求对象
     * @param response 响应对象
     */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//1.接收网页传来的数据
		String uname=request.getParameter("username");
		String upsw=request.getParameter("userpsw");
		String upswMD5=StringUtil.getMD5(upsw);
		//2.连接数据库把接收到的数据写入表里
		Connection conn=null;
		PreparedStatement pstmt=null;
		conn=DBUtil.getConnection();
		int flag=0;
		String sql="INSERT INTO financeuser VALUES(?,?,?)";
		try {
			pstmt=conn.prepareStatement(sql);
			pstmt.setString(1, (int)(Math.random()*1000)+"");   //1表示第一个?,random会生成一个0到1000的随机整数
			pstmt.setString(2, uname);
			pstmt.setString(3,upswMD5);
			flag=pstmt.executeUpdate();  //下达执行指令
			if(flag==0) {
				response.sendRedirect("fail.jsp");
			}else {
				response.sendRedirect("ok.jsp");
			}
		} catch (SQLException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}finally {
			//3.关闭数据库资源
			DBUtil.backConn(conn, pstmt, null);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	 /**
     * 处理网页发来的Get请求
     * @param request 请求对象
     * @param response 响应对象
     */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
